<?php

/**
 * Author: xx.com
 * Date: 2016-03-09
 */

namespace Admin\Controller;

use Think\AjaxPage;
use Admin\Logic\GoodsLogic;
use Common\Logic\GroupbuyLogic;

class PromotionController extends BaseController
{
	// 清仓活动类型
	private $prom_type = [
		'0' => '满额打折', 
		'1' => '满额优惠金额', 
		'2' => '满额送积分', 
		'3' => '满额送优惠券'
	];

	public function index()
	{
		$this->display();
	}

	/**
	 * 商品活动列表
	 */
	public function prom_goods_list()
	{
		$parse_type = $this->prom_type;;
		$level = M('user_level')->select();
		if ($level) {
			foreach ($level as $v) {
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
		$this->assign("parse_type", $parse_type);

		$where['is_close'] = 0;
		if ($this->shop_info) {
			$where['shop_id'] = $this->shop_info['shop_id'];
		}

		$count = M('prom_goods')->where($where)->count();
		$Page = new \Think\Page($count, 10);
		$show = $Page->show();
		$res = M('prom_goods')->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->select();
		if ($res) {
			foreach ($res as $okey => $val) {
				if (!empty($val['group']) && !empty($lv)) {
					$val['group'] = explode(',', $val['group']);
					foreach ($val['group'] as $v) {
						$val['group_name'] .= $lv[$v] . ',';
					}
				}
				$val['shop_info'] = M('shop')->where([
					'id' => $val['shop_id']
				])->field('id,shop_name')->find();
				$prom_list[] = $val;
			}
		}
		$this->prom_goods_overdue();
		$this->assign('page', $show);// 赋值分页输出
		$this->assign('prom_list', $prom_list);
		$this->display();
	}


	public function prom_goods_overdue()
	{
		$nowTime = time();
		$model = M('prom_goods');
		$update = $model->where("end_time<'$nowTime'")->save(array('is_close' => 1));
		return $update;
	}


	public function prom_goods_info()
	{
		$level = M('user_level')->select();
		$this->assign('level', $level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
		$info['end_time'] = date('Y-m-d', time() + 3600 * 60 * 24);
		if ($prom_id > 0) {
			$info = M('prom_goods')->where("id=$prom_id")->find();
			$info['start_time'] = date('Y-m-d', $info['start_time']);
			$info['end_time'] = date('Y-m-d', $info['end_time']);
			$prom_goods = M('goods')->where("prom_id=$prom_id and prom_type=3")->select();
			$this->assign('prom_goods', $prom_goods);
		}
		$this->assign('info', $info);
		$this->assign('min_date', date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}

	public function prom_goods_save()
	{
		if (!$this->shop_info||!$this->shop_info['shop_id']) {
			return $this->error('请使用商户账户操作');
		}
		$prom_id = I('id');
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		//促销时间调整 结束日期设为 结束日期当天 23:59:59
		$data['end_time'] = $data['end_time'] . ' 23:59:59';
		$data['end_time'] = strtotime($data['end_time']);
		$data['group'] = implode(',', $data['group']);
		$data['shop_id'] = $this->shop_info['shop_id'];
		if ($prom_id) {
			M('prom_goods')->where([
				"id" => $prom_id,
				"shop_id" => $this->shop_info['shop_id'],
			])->save($data);
			$last_id = $prom_id;
			adminLog("管理员修改了商品促销 " . I('name'));
		} else {
			$last_id = M('prom_goods')->add($data);
			adminLog("管理员添加了商品促销 " . I('name'));
		}

		if (is_array($data['goods_id'])) {
			$goods_id = implode(',', $data['goods_id']);
			if ($prom_id > 0) {
				M("goods")->where("prom_id=$prom_id and prom_type=3")->save(array('prom_id' => 0, 'prom_type' => 0));
			}
			M("goods")->where("goods_id in($goods_id)")->save(array('prom_id' => $last_id, 'prom_type' => 3));
		}
		$this->success('编辑促销活动成功', U('Promotion/prom_goods_list'));
	}

	public function prom_goods_del()
	{
		$prom_id = I('id');
		$prom = M('prom_goods')->where([
			'id' => $prom_id 
		])->find();
		if( !$prom ) return $this->error('无记录');
		if ($this->shop_info&&!$this->shop_info['shop_id']!=$prom['shop_id']) {
			return $this->error('无权限删除');
		}
		$order_goods = M('order_goods')->where("prom_type = 3 and prom_id = $prom_id")->find();
		
		if (!empty($order_goods)) {
			$this->error("该活动有订单参与不能删除!");
		}
		M("goods")->where("prom_id=$prom_id and prom_type=3")->save(array('prom_id' => 0, 'prom_type' => 0));
		M('prom_goods')->where("id=$prom_id")->delete();
		$this->success('删除活动成功', U('Promotion/prom_goods_list'));
	}


	/**
	 * 团购列表
	 */
	public function group_buy_list()
	{
		$where['status'] = 1;
		if ($this->shop_info) {
			$where['shop_id'] = $this->shop_info['shop_id'];
		}

		$Ad = M('group_buy');
		$count = $Ad->where($where)->count();
		$Page = new \Think\Page($count, 10);
		$res = $Ad->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->select();
		if ($res) {
			foreach ($res as $val) {
				$val['start_time'] = date('Y-m-d H:i', $val['start_time']);
				$val['end_time'] = date('Y-m-d H:i', $val['end_time']);
				$val['shop_info'] = M('shop')->where([
					'id' => $val['shop_id']
				])->field('id,shop_name')->find();
				$list[] = $val;
			}
		}
		$this->group_buy_overdue();//关闭超时的团购
		GroupbuyLogic::closeGroupBuyOrder();//关闭超时订单
		$this->assign('list', $list);
		$show = $Page->show();
		$this->assign('page', $show);
		$this->display();
	}


	/**
	 * 团购编辑
	 */
	public function group_buy()
	{
		$act = I('GET.act', 'add');
		$groupbuy_id = I('get.id');
		$group_info = array();
		$group_info['start_time'] = date('Y-m-d');
		$group_info['end_time'] = date('Y-m-d', time() + 3600 * 365);
		if ($groupbuy_id) {
			$where['id'] = $groupbuy_id;

			if ($this->shop_info) {
				$where['shop_id'] = $this->shop_info['shop_id'];
			}

			$group_info = D('group_buy')->where($where)->find();

			if (!$group_info || !$group_info['status'])
				$this->error("团购不存在");

			$group_info['start_time'] = date('Y-m-d H:i', $group_info['start_time']);
			$group_info['end_time'] = date('Y-m-d H:i', $group_info['end_time']);
			$act = 'edit';

			#读取规格参数信息
			$group_info['good_specs'] = json_decode($group_info['good_specs'], true);
			if (!empty($group_info['good_specs'])) {
				$specModel = M("spec_goods_price");
				foreach ($group_info['good_specs'] as $k => &$v) {
					$spec = $specModel->where([
						"goods_id" => $group_info['goods_id'],
						"key" => $k
					])->field("key,key_name,store_count,price as o_price")->find();

					$v = array_merge($v, $spec);
				}
			}
		}
		$this->assign('min_date', date('Y-m-d'));
		$this->assign('info', $group_info);
		$this->assign('act', $act);
		$this->display();
	}

	// 一键关闭超时的团购
	public function group_buy_overdue()
	{
		$nowTime = time();
		$model = M('group_buy');
		$update = $model->where("end_time<'$nowTime'")->save(array('status' => 0));
		return $update;
	}


	/**
	 * 团购添加或者删除
	 */
	public function groupbuyHandle()
	{
		$data = I('post.');

		if ($this->shop_info) {
			$whereGoods['shop_id'] = $where['shop_id'] = $this->shop_info['shop_id'];
		}

		// 删除
		if ($data['act'] == 'del') {
			if (empty($data['id']))
			return $this->error('参数错误');

			$where['id'] = $data['id'];
    		// $r = D('group_buy')->where('id='.$data['id'])->delete();
			$r = D('group_buy')->where($where)->save([
				"status" => 0
			]);
    		// M('goods')->where("prom_type=2 and prom_id=".$data['id'])->save(array('prom_id'=>0,'prom_type'=>0));
			if ($r !== false) exit(json_encode(1));

			exit(json_encode(0));
		}

		// var_dump($data);
		// exit();

		$goods_id = I("post.goods_id");
		if (empty($goods_id)) {
			return $this->error("尚未选择商品");
		}

		if (!isset($data['title']) || !isset($data['start_time']) || !isset($data['end_time']) || !isset($data['price']) || !isset($data['per_num']) || !isset($data['goods_num']))
			return $this->error("参数错误");

		if ($data['goods_num'] / $data['per_num'] < 1) {
			return $this->error("参团商品数量无法满足开团条件");
		}

		$whereGoods['goods_id'] = $goods_id;
		$whereGoods['is_on_sale'] = 1;

		$goodsInfo = M('Goods')->where($whereGoods)->find();

		if (!$goodsInfo) {
			return $this->error("商品不存在");
		}

		#处理规格信息
		$specs = M("spec_goods_price")->where("goods_id = {$goods_id}")->select();

		if ($specs) {
			if (!isset($data['spec']) || empty($data['spec']) || count($specs) != count($data['spec'])) {
				return $this->error("所选商品为多规格，必须设置相应规格的参团参数");
			}

			$good_specs = [];

			$total = 0;

			foreach ($specs as $k => $v) {
				if (!isset($data['spec'][$v['key']])) {
					continue;
				}

				if ($data['spec'][$v['key']]['price'] < 0) {
					return $this->error("所有规格商品价格不得小于0");
				}

				$total = $total + $data['spec'][$v['key']]['num'];

				$good_specs[$v['key']] = $data['spec'][$v['key']];

			}

			if (empty($good_specs)) {
				return $this->error("所选商品为多规格，必须设置相应规格的参团参数");
			}

			if ($total != $data['goods_num']) {
				return $this->error('各规格总商品数和参与团购商品总数设置不一致');
			}
			unset($k);
			unset($v);

			$data['good_specs'] = json_encode($good_specs);

		} else {
			$data['good_specs'] = '';
		}

		$data['shop_id'] = $goodsInfo['shop_id'];

		#记录原价
		$data['goods_price'] = $goodsInfo['shop_price'];

		#记录名称
		$data['goods_name'] = $goodsInfo['goods_name'];

		#记录店铺id
		$data['shop_id'] = $goodsInfo['shop_id'];

		$data['intro'] = htmlspecialchars(stripslashes($_POST['intro']));
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['max_buy_num'] = intval($data['max_buy_num']);

		$data['update_time'] = time();

		M()->startTrans();
        
    	// 更新
		if ($data['act'] == 'edit') {
			if (empty($data['id']))
			return $this->error('参数错误');
			$old = D('group_buy')->where('id=' . $data['id'])->find();

			if (!$old) {
				$r = D('group_buy')->add($data);
			} else {
				if ($old['goods_id'] != $data['goods_id']) {
					M()->rollback();
					$this->error("不允许更换团购商品");
				}

				if ($old['per_num'] != $data['per_num']) {
					$groupUpdate = M("group_info")->where([
						"group_buy_id" => $old['id'],
						"status" => 0
					])->save([
						"per_num" => $data['per_num']
					]);

					if ($groupUpdate === false) {
						M()->rollback();
						return $this->error("更新失败");
					}
				}

				$r = D('group_buy')->where('id=' . $data['id'])->save($data);
				// M('goods')->where("prom_type=2 and prom_id=".$data['id'])->save(array('prom_id'=>0,'prom_type'=>0));
				// M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$data['id'],'prom_type'=>2));
			}
		}
		// 添加
		if ($data['act'] == 'add') {
			$data['create_time'] = $data['update_time'];
			$r = D('group_buy')->add($data);
			$u = M('goods')->where("goods_id=" . $data['goods_id'])->save(array('prom_id' => $r, 'prom_type' => 2));

			if ($u === false) {
				M()->rollback();
				return $this->error("更新失败");
			}
		}

		if ($r) {
			M()->commit();
			return $this->success("操作成功", U('Admin/Promotion/group_buy_list'));
		} else {
			M()->rollback();
			return $this->error("操作失败", U('Admin/Promotion/group_buy_list'));
		}
	}

	public function get_goods()
	{
		$prom_id = I('id');

		$where['prom_type'] = 3;
		$where['prom_id'] = $prom_id;

		if ($this->shop_info) {
			$where['shop_id'] = $this->shop_info['shop_id'];
		}

		$count = M('goods')->where($where)->count();
		$Page = new \Think\Page($count, 10);
		$goodsList = M('goods')->where($where)->order('goods_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
		$show = $Page->show();
		$this->assign('page', $show);
		$this->assign('goodsList', $goodsList);
		$this->display();
	}

	public function search_goods()
	{
		$GoodsLogic = new \Admin\Logic\GoodsLogic;
		$brandList = $GoodsLogic->getSortBrands();
		$this->assign('brandList', $brandList);
		$categoryList = $GoodsLogic->getSortCategory();
		$this->assign('categoryList', $categoryList);

		$goods_id = I('goods_id');
		$where = ' is_on_sale = 1 and prom_type=0 and store_count>0 ';//搜索条件

		if ($this->shop_info) {
			$where .= " and shop_id=" . $this->shop_info['shop_id'];
		}

		if (!empty($goods_id)) {
			$where .= " and goods_id not in ($goods_id) ";
		}
		I('intro') && $where .= " and " . I('intro') . " = 1";
		if (I('cat_id')) {
			$this->assign('cat_id', I('cat_id'));
			$grandson_ids = getCatGrandson(I('cat_id'));
			$where .= " and cat_id in(" . implode(',', $grandson_ids) . ") "; // 初始化搜索条件
		}
		if (I('brand_id')) {
			$this->assign('brand_id', I('brand_id'));
			$where .= " and brand_id = " . I('brand_id');
		}
		if (!empty($_REQUEST['keywords'])) {
			$this->assign('keywords', I('keywords'));
			$where .= " and (goods_name like '%" . I('keywords') . "%' or keywords like '%" . I('keywords') . "%')";
		}
		$count = M('goods')->where($where)->count();
		$Page = new \Think\Page($count, 10);
		$goodsList = M('goods')
			->where($where)
			->order('goods_id DESC')
			->limit($Page->firstRow . ',' . $Page->listRows)
			->fetchSql(0)
			->select();
		$show = $Page->show();//分页显示输出
		$this->assign('page', $show);//赋值分页输出
		$this->assign('goodsList', $goodsList);
		$tpl = I('get.tpl', 'search_goods');
		$this->display($tpl);
	}

    //限时抢购
	public function flash_sale()
	{
		$condition = array();
		$nowTime = time();

		$where['fs.end_time'] = ['gt', $nowTime];

		if ($this->shop_info) {
			$where['fs.shop_id'] = $this->shop_info['shop_id'];
		}

		$model = M('flash_sale as fs');
		$count = $model->where($where)->count();
		$Page = new \Think\Page($count, 10);
		$show = $Page->show();
		$prom_list = $model
			->join('ln_kill as k on k.kill_id=fs.kill_id')
			->field('fs.id,k.kill_time,fs.goods_num,fs.goods_name,fs.order_num,fs.start_time,fs.end_time,fs.buy_num,is_end,fs.shop_id')
			->where($where)
			->order("id desc")
			->limit($Page->firstRow . ',' . $Page->listRows)
			->fetchSql(0)
			->select();
			// var_dump($prom_list);die;
		foreach($prom_list as $k => &$v)
		{
			$v['shop_info'] = M('shop')->where([
				'id' => $v['shop_id']
			])->field('id,shop_name')->find();
			// var_dump($v);
		}
		$this->flash_sale_overdue();
		$this->assign('prom_list', $prom_list);
		$this->assign('page', $show);// 赋值分页输出
		$this->display();
	}

    //限时抢购商品添加
	public function flash_sale_info()
	{
		if (IS_POST) {
			$nowTime = date("H:i");
			$nowTime2 = substr($nowTime, 0, 2);
			$data = I('post.');
			$where['is_on_sale'] = 1;
			$where['goods_id'] = $data['goods_id'];
			if ($this->shop_info) {
				$where['shop_id'] = $this->shop_info['shop_id'];
			}
			$goodsInfo = M('goods')->field('goods_name,shop_id,store_count')->where($where)->find();

			if (!$goodsInfo) {
				return $this->error("商品已下架或不存在");
			}

			if (intval($data['goods_num']) > $goodsInfo['store_count']) {
				return $this->error('抢购数量大于库存数量，请重新填写');
			}
			$kill_id = $data['kill_id'];
			$kill = M('kill')->field('kill_time')->where([
				"kill_id" =>$kill_id
			])->select();
			$kill_time = $kill[0]['kill_time'];
			$kill_time2 = substr($kill_time, 0, 2);
            // if ($kill_time2<$nowTime2) {
            //     $this->error('抢购时间不能小于当前时间，请重新填写',U('Promotion/flash_sale_info'));
			// }
			$data['shop_id'] = $goodsInfo['shop_id'];
			$data['start_time'] = strtotime(date("Y-m-d $kill_time2:00:00"));
			$data['end_time'] = strtotime(date("Y-m-d H:i:s", strtotime("+1 day", $data['start_time'])));
			if (empty($data['id'])) {
				$r = M('flash_sale')->add($data);
				M('goods')->where("goods_id=" . $data['goods_id'])->save(array('prom_id' => $r, 'prom_type' => 1));
				adminLog("管理员添加抢购活动 " . $data['name']);
			} else {
				$r = M('flash_sale')->where("id=" . $data['id'])->save($data);
				M('goods')->where("prom_type=1 and prom_id=" . $data['id'])->save(array('prom_id' => 0, 'prom_type' => 0));
				M('goods')->where("goods_id=" . $data['goods_id'])->save(array('prom_id' => $data['id'], 'prom_type' => 1));
			}
			if ($r) {
				$this->success('编辑抢购活动成功', U('Promotion/flash_sale'));
				exit;
			} else {
				$this->error('编辑抢购活动失败', U('Promotion/flash_sale'));
			}
		}
		$id = I('id');
		$data['start_time'] = strtotime(date("Y-m-d $kill_time2:00:00"));
		$data['end_time'] = strtotime(date("Y-m-d H:i:s", strtotime("+1 day", $data['start_time'])));
		if ($id > 0) {
			$where['id'] = $id;
			if ($this->shop_info) {
				$where['shop_id'] = $this->shop_info['shop_id'];
			}
			$info = M('flash_sale')->where($where)->find();
			$info['start_time'] = date('Y-m-d H:i', $info['start_time']);
			$info['end_time'] = date('Y-m-d H:i', $info['end_time']);
		}
		$kill_time = M('kill')->select();
		$this->assign('kill_time', $kill_time);
		$this->assign('info', $info);
		$this->assign('min_date', date('Y-m-d'));
		$this->display();
	}


    //限时秒杀过期活动列表
	public function flash_sale_overdue()
	{
		$nowTime = time();
		$model = M('flash_sale');
		$update = $model->where("end_time<'$nowTime'")->save(array('is_end' => 1));
		return $update;
	}

	public function flash_sale_del()
	{
		$id = I('del_id');
		if ($id) {
			$where['id'] = $id;
			if ($this->shop_info) {
				$where['shop_id'] = $this->shop_info['shop_id'];
			}
			M()->startTrans();
			$a = M('flash_sale')->where($where)->delete();
			$b = M('goods')->where("prom_type=1 and prom_id=$id")->save(array('prom_id' => 0, 'prom_type' => 0));

			if ($a && $b) {
				M()->commit();
				exit(json_encode(1));
			}
			M()->rollback();
		}
		exit(json_encode(0));
	}

	private function initEditor()
	{
		$this->assign("URL_upload", U('Admin/Ueditor/imageUp', array('savepath' => 'promotion')));
		$this->assign("URL_fileUp", U('Admin/Ueditor/fileUp', array('savepath' => 'promotion')));
		$this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp', array('savepath' => 'promotion')));
		$this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage', array('savepath' => 'promotion')));
		$this->assign("URL_imageManager", U('Admin/Ueditor/imageManager', array('savepath' => 'promotion')));
		$this->assign("URL_imageUp", U('Admin/Ueditor/imageUp', array('savepath' => 'promotion')));
		$this->assign("URL_getMovie", U('Admin/Ueditor/getMovie', array('savepath' => 'promotion')));
		$this->assign("URL_Home", "");
	}

	// 以下的并没有改功能，就不改了， 

	public function prom_order_info()
	{
		$this->assign('min_date', date('Y-m-d'));
		$level = M('user_level')->select();
		$this->assign('level', $level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
		$info['end_time'] = date('Y-m-d', time() + 3600 * 24 * 60);
		if ($prom_id > 0) {
			$info = M('prom_order')->where("id=$prom_id")->find();
			$info['start_time'] = date('Y-m-d', $info['start_time']);
			$info['end_time'] = date('Y-m-d', $info['end_time']);
		}
		$this->assign('info', $info);
		$this->assign('min_date', date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}

	public function prom_order_save()
	{
		$prom_id = I('id');
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['group'] = implode(',', $data['group']);
		if ($prom_id) {
			M('prom_order')->where("id=$prom_id")->save($data);
			adminLog("管理员修改了商品促销 " . I('name'));
		} else {
			M('prom_order')->add($data);
			adminLog("管理员添加了商品促销 " . I('name'));
		}
		$this->success('编辑促销活动成功', U('Promotion/prom_order_list'));
	}

	public function prom_order_del()
	{
		$prom_id = I('id');
		$order = M('order')->where("order_prom_id = $prom_id")->find();
		if (!empty($order)) {
			$this->error("该活动有订单参与不能删除!");
		}

		M('prom_order')->where("id=$prom_id")->delete();
		$this->success('删除活动成功', U('Promotion/prom_order_list'));
	}

	/**
	 * 活动列表
	 */
	public function prom_order_list()
	{
		// $parse_type = array('0' => '满额打折', '1' => '满额优惠金额', '2' => '满额送积分', '3' => '满额送优惠券');
		$parse_type = $this->prom_type;
		$level = M('user_level')->select();
		if ($level) {
			foreach ($level as $v) {
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
		$count = M('prom_order')->count();
		$Page = new \Think\Page($count, 10);
		$show = $Page->show();
		$res = M('prom_order')->limit($Page->firstRow . ',' . $Page->listRows)->select();
		if ($res) {
			foreach ($res as $val) {
				if (!empty($val['group']) && !empty($lv)) {
					$val['group'] = explode(',', $val['group']);
					foreach ($val['group'] as $v) {
						$val['group_name'] .= $lv[$v] . ',';
					}
				}
				$prom_list[] = $val;
			}
		}
		$this->assign('page', $show);// 赋值分页输出
		$this->assign("parse_type", $parse_type);
		$this->assign('prom_list', $prom_list);
		$this->display();
	}

	/**
	 * 兑换列表
	 */
	public function exchange_buy_list()
	{
		$where['status'] = 1;
		if ($this->shop_info) {
			$where['shop_id'] = $this->shop_info['shop_id'];
		}

		$Ad = M('exchange_buy');
		$count = $Ad->where($where)->count();
		$Page = new \Think\Page($count, 10);
		$list = $Ad->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->select();
		// GroupbuyLogic::closeGroupBuyOrder();//关闭超时订单
		$goodsModel = M('goods');
		foreach($list as $k => &$v)
		{
			$v['goods_info'] = $goodsModel
					->where([
						'goods_id' => $v['goods_id'],
					])
					->field('goods_id,goods_name,original_img')
					->find();
			$v['shop_info'] = M('shop')->where([
				'id' => $v['shop_id']
			])->field('id,shop_name')->find();
		}
		$this->assign('list', $list);
		$show = $Page->show();
		$this->assign('page', $show);
		$this->display();
	}


	/**
	 * 兑换编辑
	 */
	public function exchange_buy()
	{
		$act = I('GET.act', 'add');
		$groupbuy_id = I('get.id');
		$group_info = array();
		$model = M('exchange_buy');
		if ($groupbuy_id) {
			$where['id'] = $groupbuy_id;

			if ($this->shop_info) {
				$where['shop_id'] = $this->shop_info['shop_id'];
			}

			$group_info = $model->where($where)->find();

			if (!$group_info)
				$this->error("兑换商品不存在");
				
			$act = 'edit';

			#商品信息
			$group_info['goods_name'] = M('goods')->where([
				'goods_id' => $group_info['goods_id']
			])->getField('goods_name');

			#读取规格参数信息
			$group_info['good_specs'] = json_decode($group_info['good_specs'], true);
			if (!empty($group_info['good_specs'])) {
				$specModel = M("spec_goods_price");
				foreach ($group_info['good_specs'] as $k => &$v) {
					$spec = $specModel->where([
						"goods_id" => $group_info['goods_id'],
						"key" => $k
					])->field("key,key_name,store_count,price as o_price")->find();

					$v = array_merge($v, $spec);
				}
			}
		}
		$this->assign('min_date', date('Y-m-d'));
		$this->assign('info', $group_info);
		$this->assign('act', $act);
		$this->display();
	}

	/**
	 * 兑换添加或者删除
	 */
	public function exchangebuyHandle()
	{
		$data = I('post.');

		if ($this->shop_info) {
			$whereGoods['shop_id'] = $where['shop_id'] = $this->shop_info['shop_id'];
		}

		// 删除
		if ($data['act'] == 'del') {
			if (empty($data['id']))
			return $this->error('参数错误');

			$where['id'] = $data['id'];
    		$r = D('exchange_buy')->where('id='.$data['id'])->delete();
			// $r = D('exchange_buy')->where($where)->save([
			// 	"status" => 0
			// ]);
			if ($r !== false) exit(json_encode(1));

			exit(json_encode(0));
		}

		// var_dump($data);
		// exit();

		$goods_id = I("post.goods_id");
		if (empty($goods_id)) {
			return $this->error("尚未选择商品");
		}

		if ( !isset($data['price']) || !isset($data['goods_num']))
			return $this->error("参数错误");

		$whereGoods['goods_id'] = $goods_id;
		$whereGoods['is_on_sale'] = 1;

		$goodsInfo = M('Goods')->where($whereGoods)->find();

		if (!$goodsInfo) {
			return $this->error("商品不存在或者已下架");
		}

		#处理规格信息
		$specs = M("spec_goods_price")->where("goods_id = {$goods_id}")->select();

		if ($specs) {
			if (!isset($data['spec']) || empty($data['spec']) || count($specs) != count($data['spec'])) {
				return $this->error("所选商品为多规格，必须设置相应规格的参团参数");
			}

			$good_specs = [];

			$total = 0;

			foreach ($specs as $k => $v) {
				if (!isset($data['spec'][$v['key']])) {
					continue;
				}

				if ($data['spec'][$v['key']]['price'] < 0) {
					return $this->error("所有规格商品价格不得小于0");
				}

				$total = $total + $data['spec'][$v['key']]['num'];

				$good_specs[$v['key']] = $data['spec'][$v['key']];

			}

			if (empty($good_specs)) {
				return $this->error("所选商品为多规格，必须设置相应规格的参数");
			}

			if ($total != $data['goods_num']) {
				return $this->error('各规格总商品数和参与商品总数设置不一致');
			}
			unset($k);
			unset($v);

			$data['good_specs'] = json_encode($good_specs);

		} else {
			$data['good_specs'] = '';
		}

		$data['shop_id'] = $goodsInfo['shop_id'];
		$data['max_buy_num'] = intval($data['max_buy_num']);

		$data['update_time'] = time();

		M()->startTrans();

		$model = M('exchange_buy');

		// p($data);die;
        
    	// 更新
		if ($data['act'] == 'edit') {
			if (empty($data['id']))
			return $this->error('参数错误');
			$old = $model->where('id=' . $data['id'])->find();

			if (!$old) {
				$r = $model->add($data);
			} else {
				if ($old['goods_id'] != $data['goods_id']) {
					M()->rollback();
					$this->error("不允许更换商品");
				}

				$r = $model->where('id=' . $data['id'])->save($data);
			}
		}
		// 添加
		if ($data['act'] == 'add') {
			$data['create_time'] = $data['update_time'];
			$r = $model->add($data);
		}

		if ($r) {
			M()->commit();
			return $this->success("操作成功", U('Admin/Promotion/exchange_buy_list'));
		} else {
			M()->rollback();
			return $this->error("操作失败", '');
		}
	}
}